<template>
	<view class="page">
		<u-navbar title="详情" is-fixed :background="background"></u-navbar>
		<view class="picture">
			<image class="img" :src="detailInfo.bigimage?detailInfo.bigimage:detailInfo.cover_image" mode="aspectFill">
			</image>
			<view class="icon" @click="changeCollect" v-if="pageType!='jiayouzhan'">
				<u-icon v-if="!isCollect" name="star" size='30' color='#ccc'></u-icon>
				<u-icon v-else name="star-fill" size='30' color='#fe466b'></u-icon>
			</view>
			<view class="wechat-image" v-if="pageType=='share'" @click="clickQrcode">
				<i class="iconfont icon-qrcode-1-copy" style="color:#fe466b;"></i>
			</view>
			<view v-if="pageType=='case'||pageType=='lecture'" class="wechat-image" @click="tokefu">
				<u-icon name="server-fill" color='#FE5477' size="40"></u-icon>
			</view>
			<view v-if="pageType=='lecture'" class="teacher-info">
				<u-avatar :src="detailInfo.team_info.image" size='mini'></u-avatar>
				<view class="teacher-name">
					{{detailInfo.team_info.name}}
				</view>
			</view>
		</view>
		<view class="audio-view">
			<view class="play-button-area">
				<image class="icon-play" :src="playImage" @click="play"></image>
				<u-icon class="icon-play" :name="playImage" color="#fe466b" size="60" @click="play"></u-icon>
			</view>
			<view class="play-silder">
				<view class="audio-time">
					<text>{{currentTimeStr}}</text>
				</view>
				<view class="audio-siler">
					<slider :value="position" :min="0" :max="duration.toFixed(0)" :block-size="blockSize"
						:backgroundColor='backgroundColor' :activeColor='activeColor' @changing="onchanging"
						@change="onchange">
					</slider>
				</view>
				<view class="audio-time">
					<text>{{timeStr}}</text>
				</view>
			</view>
		</view>
		<view class="detail">
			<text class="name">{{detailInfo.title || detailInfo.name}}</text>
			<view class="secend-line">
				<u-icon class='icon' name="eye"></u-icon><text>{{detailInfo.reading_volume}}</text>
				<u-icon class='icon' name="calendar"></u-icon>
				<text>{{detailInfo.createtime | date('yyyy-mm-dd hh:MM:ss')}}</text>
				<!-- <u-icon class='icon' name="clock"></u-icon><text></text> -->
			</view>
		</view>
		<scroll-view class="text" :scroll-y="true" :style="'height:' + scrollH+'rpx;'"
			v-if="detailInfo.outline_content || detailInfo.content">
			<view class="" v-if="detailInfo.outline_content">
				<!-- <view class="font-style-xie">大纲</view> -->
				<u-parse style='margin: 20rpx 0;' :html="detailInfo.outline_content"></u-parse>
			</view>
			<view class="" v-if="detailInfo.content">
				<!-- <view class="font-style-xie">详情</view> -->
				<u-parse :html="detailInfo.content"></u-parse>
			</view>

		</scroll-view>
		<!-- 更多视频 -->
		<view class="model" v-if="detailInfo.otherLst">
			<view class="font-style-xie">更多<text class="video-num">数量：{{detailInfo.otherLst.length}}</text></view>
			<scroll-view class="scroll-view_H" scroll-x="true">
				<view class="show-item" v-for="(item, index) in detailInfo.otherLst" :key="item.id">
					<view class="image" @click="toPlay(item)">
						<image class="image" :src="item.cover_image" mode=""></image>
					</view>
				</view>
			</scroll-view>
		</view>
		<qr-madel :src='detailInfo.wechat_image' :show='showQrcode'></qr-madel>
		<u-modal v-model="messageShow" :content="pageFilter(pageType)" @confirm='messageConfirm' show-cancel-button></u-modal>
	</view>
</template>

<script>
	import qrMadel from '../components/qrcodeModal.vue'
	import {requestSubscribeMessage} from '@/mixin/RSMessage.js'
	export default {
		components: {
			qrMadel
		},
		mixins: [requestSubscribeMessage],
		data() {
			return {
				messageShow:false,
				modal_content:'',
				isCollect: 0,
				isPlaying: false,
				isPlayEnd: false,
				blockSize: 12, //控制滑块的大小
				backgroundColor: '#ccc', //滑块右侧背景条的颜色
				activeColor: '#fe466b', //滑块左侧已选择部分的线条颜色
				duration: 100,
				currentTime: 0,
				currentTimeStr: '00:00',
				timeStr: '00:00',
				audioUrl: '',
				baseUrl: this.$u.http.config.baseUrl,
				detailInfo: '',
				pageType: "",
				showQrcode: false,
				id: '',
				background: {
					backgroundColor: '#FFF',
					background: 'url(https://www.yplm888.com//uploads/20220803/7ed305f9a93ba50b049a7725662b18cc.png) no-repeat',
				},
				src: '',
				scrollH: 0
			}
		},
		computed: {
			position() {
				return this.isPlayEnd ? 0 : this.currentTime;
			},
			playImage() {
				return this.isPlaying ? "pause-circle-fill" : "play-circle-fill";
			}
		},
		onReady() {},
		async onLoad(option) {
			this.pageType = option.pageType;
			this.id = option.id;
			this.teacherId = option.teacherId || '';
			await this.getDetail(option.id, this.pageType);
			uni.setNavigationBarTitle({
				title: option.title
			});
			this._isChanging = false;
			this._audioContext = null;
			this.createAudio();
			uni.showLoading({
				title: '音频加载中'
			})
			if ((this.baseUrl + this.audioUrl) == this.$store.state.musicSrc) {
				uni.hideLoading()
			}
			let that = this;
			let hight = this.detailInfo.otherLst ? 1150 : 880;
			uni.getSystemInfo({
				success: function(res) {
					that.scrollH = res.windowHeight * 750 / res.windowWidth;
					// #ifdef MP-WEIXIN
					that.scrollH = res.windowHeight * 750 / res.windowWidth - parseInt(res.safeArea.top) -
						hight;
					// #endif
				}
			});
			this.getMessageStatus();
		},
		onUnload() {
			// if (this._audioContext != null && this.isPlaying) {
			// 	this.stop();
			// }
		},
		watch: {
			audioUrl(val) {
				if (this._audioContext != null && this.isPlaying) {
					this.stop();
				}
			}
		},
		methods: {
			pageFilter(val){
				let page = {
					'case': '经典案例',
					'share': '经验分享',
					'lecture': '主题讲座',
					'liveBack': '直播回放', 
					'teamLeader':'组长团队', 
					'broandStory': '品牌故事', 
					'class':'课程', 
					'leader':'组长团队', 
					'Journa':'新闻咨询',
				}
				return '是否订阅'+page[val]+'上新通知?';
			},
			toPlay(data) {
				if (data.type == 0) {
					this.getDetail(data.id, this.pageType);
				} else {
					this.$u.route('/packageB/pages/videosDetail/videosDetail', {
						id: data.id,
						title: data.name,
						pageType: this.pageType
					})
				}
			},
			// 客服
			async tokefu() {
				await this.getConfig();
				let res;
				if (this.pageType == 'case') {
					res = await this.$u.api.caseService();
				} else if (this.pageType == 'lecture') {
					res = await this.$u.api.customerSerivce();
				}
				this.toChat(res.data);
			},
			getConfig() {
				this.$u.api.getChatConfig().then(res => {
					this.config = res.data.corpId;
				})
			},
			toChat(data) {
				try {
					wx.openCustomerServiceChat({
						extInfo: {
							url: data.url //客服ID
						},
						corpId: this.config, //企业微信ID
						success(res) {}
					})
				} catch (error) {}
			},
			// 点击二维码
			clickQrcode() {
				this.showQrcode = true
			},
			// 获取详情
			async getDetail(id, pageType) {
				let queryTypeObject = {
					case: 'getCaseDetail',
					share: 'getShareDetail',
					lecture: 'getLectureDetail',
					teamLeader: 'groupAudioList',
					Journa: 'JournalismDetail',
					liveBack: 'getLivebackInfo',
					broandStory: 'BrandstoryInfo',
					jiayouzhan: 'CultivateDetail',
					analysis: 'AnalysisDetail'
				}
				let queryType = queryTypeObject[pageType]
				await this.$u.api[queryType]({
					id
				}).then(res => {
					this.detailInfo = res.data;
					this.audioUrl = res.data.file || res.data.audio_file;
					this.isCollect = res.data.is_collection;
					if (res.data.is_subscribe == 0) {
						this.messageShow = true;
					}
				})
			},
			// 收藏
			changeCollect() {
				let typeList = ['junshi', 'case', 'share', 'lecture', "liveBack", 'teamLeader', 'broandStory', 'class',
					'leader', 'Journa', 'jiayouzhan','analysis'
				];
				let type = typeList.indexOf(this.pageType);
				this.$u.api.collect({
					collection_id: this.detailInfo.id,
					collection_type: type + 1
				}).then(res => {
					if (res.code == 1) {
						this.isCollect = this.isCollect ? 0 : 1;
						uni.showToast({
							title: res.msg
						});
					}
				});
			},
			// 音频播放
			createAudio() {
				let innerAudioContext = this._audioContext = uni.getBackgroundAudioManager();
				let src = '';
				if (this.audioUrl.indexOf("www") >= 0 || this.audioUrl.indexOf("http") >= 0 || this.audioUrl.indexOf("https") >= 0) 
				{
					src = this.audioUrl;
				} else {
					src = this.baseUrl + this.audioUrl;
				}
				this.$store.commit('setMusicSrc', src);
				innerAudioContext.autoplay = false;
				innerAudioContext.src = src;
				innerAudioContext.startTime = this.detailInfo.record || 0;
				innerAudioContext.coverImgUrl = this.detailInfo.bigimage;
				innerAudioContext.title = this.detailInfo.title || this.detailInfo.name;
				innerAudioContext.onPlay(() => {
					this.isPlaying = true;
				});
				innerAudioContext.onStop(() => {
					this.isPlaying = false;
					this.reSetUrl = true;
					this.addPlayOrder();
				})
				innerAudioContext.onPause((e) => {
					this.isPlaying = false;
					this.addPlayOrder();
				})
				innerAudioContext.onCanplay(() => {
					let timeid = setInterval(() => {
						if (innerAudioContext.duration) {
							clearInterval(timeid);
							this.duration = innerAudioContext.duration || 0;
							this.timeStr = this.formatSecond(this.duration);
							uni.hideLoading();
						}
					}, 500);
				});
				innerAudioContext.onTimeUpdate((e) => {
					if (this._isChanging === true) {
						return;
					}
					this.currentTime = innerAudioContext.currentTime || 0;
					this.duration = innerAudioContext.duration || 0;
					this.currentTimeStr = this.formatTime(this.currentTime);
				});
				innerAudioContext.onEnded(() => {
					this.currentTime = 0;
					this.currentTimeStr = this.formatTime(this.currentTime);
					this.isPlaying = false;
					this.isPlayEnd = true;
					this.reSetUrl = true;
				});
				innerAudioContext.onError((res) => {
					this.isPlaying = false;
				});
				return innerAudioContext;
			},
			onchanging() {
				this._isChanging = true;
			},
			onchange(e) {
				this._audioContext.seek(e.detail.value);
				this._isChanging = false;
				const currTimeStr = this.formatTime(e.detail.value);
				this.currentTimeStr = currTimeStr;
			},
			async play() {
				if (this.reSetUrl) {
					let src = this.baseUrl + this.audioUrl;
					this._audioContext.src = src;
					this._audioContext.startTime = this.detailInfo.record || 0;
					this._audioContext.coverImgUrl = this.detailInfo.bigimage;
					this.reSetUrl = false;
				}
				if (this.isPlaying) {
					this.pause();
					return;
				}
				this._audioContext.play();
				this.isPlaying = true;
				this.isPlayEnd = false;
			},
			pause() {
				this._audioContext.pause();
				this.isPlaying = false;
			},
			stop() {
				this._audioContext.stop();
				this.isPlaying = false;
			},
			// 记录播放时间
			addPlayOrder() {
				if (this.currentTime == 0) return;
				let typeList = ['junshi', 'case', 'share', 'lecture', "liveBack", 'leader', 'broandStory', 'class',
					'teamLeader', 'Journa', 'jiayouzhan','analysis'
				];
				let typeNum = typeList.indexOf(this.pageType) + 1;
				let data = {
					curriculum_id: this.id,
					second: this.currentTime,
					curriculum_type: typeNum,
					product_id: this.teacherId
				}
				this.$u.api.ProductRecord(data).then();
			},
			formatTime(num) {
				//格式化时间格式
				num = num.toFixed(0);
				let second = num % 60;
				if (second < 10) second = '0' + second;
				let min = Math.floor(num / 60);
				if (min < 10) min = '0' + min;
				return min + ":" + second;
			},
			/**
			 * 格式化时间 
			 * @param {String} date 原始时间格式
			 * 格式后的时间：hh:mm:ss
			 **/
			formatSecond(seconds) {
				var m = (parseInt(seconds / 60) > 99) ? parseInt(seconds / 60).toString().padStart(3, '0') : parseInt(
					seconds / 60).toString().padStart(2, '0')
				var s = parseInt(seconds % 60).toString().padStart(2, '0');
				return m + ":" + s;
			}
		}
	}
</script>

<style lang="scss">
	.page {
		padding: 20rpx 40rpx;
	}

	.font-style-xie {
		font-weight: 700;
		font-size: 32rpx !important;
		font-style: italic;

		.video-num {
			font-style: normal;
			font-weight: normal;
			font-size: 16rpx;
			color: #FE5477;
			float: right;
			margin-right: 10rpx;
			margin-top: 10rpx;
		}
	}

	.picture {
		height: 400rpx;
		width: 100%;
		border-radius: 40rpx;
		background-color: #ccc;
		position: relative;

		.img {
			height: 400rpx;
			width: 100%;
			border-radius: 40rpx;
		}

		.icon {
			height: 60rpx;
			width: 60rpx;
			border-radius: 20rpx;
			background-color: #fff;
			position: absolute;
			line-height: 60rpx;
			right: 20rpx;
			bottom: 20rpx;
			text-align: center;
		}

		.wechat-image {
			height: 60rpx;
			width: 60rpx;
			border-radius: 20rpx;
			background-color: #fff;
			line-height: 60rpx;
			position: absolute;
			bottom: 20rpx;
			right: 100rpx;
			text-align: center;
		}

		.teacher-info {
			height: 70rpx;
			width: 200rpx;
			border-radius: 35rpx;
			background-color: rgba(0, 0, 0, 0.1);
			line-height: 70rpx;
			position: absolute;
			bottom: 15rpx;
			left: 20rpx;
			text-align: center;
			display: flex;

			.teacher-name {
				height: 70rpx;
				line-height: 70rpx;
				text-align: center;
				margin-left: 20rpx;
				color: #fff;
				font-weight: 700;
			}
		}
	}

	.mp3-play {
		margin-top: 60rpx;
		display: flex;
		align-items: center;

		.progress {
			margin-left: 20rpx;
			width: 90%;
		}
	}

	.audio-view {
		display: flex;
		align-items: center;
		justify-content: space-between;
		// border: 1rpx #dadada solid;
		padding: 30rpx 10rpx;
		background-color: #FFFFFF;
	}

	.play-time-area {
		display: flex;
		align-items: center;
		flex-direction: row;
	}

	.audio-time {
		width: 150rpx;
		line-height: 100rpx;
	}

	.duration {
		margin-left: auto;
	}

	.audio-siler {
		// margin-top: 10rpx;
		width: 200%;
	}

	.play-silder {
		width: 100%;
		display: flex;
		align-items: center;
		justify-content: space-around;
	}

	.play-button-area {
		display: flex;
		flex-direction: row;
		justify-content: center;
		width: 100rpx;
	}

	.icon-play {
		width: 100rpx;
		height: 100rpx;
		/* margin-top: 5rpx; */
	}

	.detail {
		margin-top: 0rpx;
		border-bottom: 1rpx solid rgba(0, 0, 0, 0.1);

		.name {
			font-size: 36rpx;
			margin-left: 10rpx;
			font-weight: 700;
			width: 90%;
		}

		.secend-line {
			color: #ccc;
			// margin-left: 40rpx;
			padding-bottom: 20rpx;

			.icon {
				margin-left: 10rpx;
				margin-right: 10rpx;
			}

		}
	}

	.text {
		margin-top: 10rpx;
	}

	.model {
		height: 300rpx;
		margin-top: 40rpx;
		// padding: 0 40rpx;

		.scroll-view_H {
			margin-top: 20rpx;
			white-space: nowrap;
			width: 100%;

			.show-item {
				display: inline-block;

				.image {
					height: 150rpx;
					width: 200rpx;
					border-radius: 20rpx;
					margin-right: 20rpx;
					background-color: #ccc;

					.image {
						height: 150rpx;
						width: 200rpx;
						border-radius: 20rpx;
					}
				}
			}
		}
	}
</style>
